//
//  Repair3ViewController.m
//  Project6
//
//  Created by ToanDK on 11/16/12.
//  Copyright (c) 2012 DungNP. All rights reserved.
//

#import "Repair3ViewController.h"
#import "EnterDataCell.h"
#import "CheckBoxCell.h"
#import "TextViewCell.h"
#import "RepairButtonCell.h"
#import "SliderCell.h"
@interface Repair3ViewController ()

@end

@implementation Repair3ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Repair";
    // set background for table
    [tblRepair3 setBackgroundView:nil];
    UIView * bgView = [[UIView alloc] initWithFrame:tblRepair3.frame];
    bgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"greyBackground.png"]];
    [tblRepair3 setBackgroundView:bgView];
    
    sectionNames = [[NSMutableArray alloc] initWithObjects:
                    @"Humidity",
                    @"Temperature",
                    @"Weather conditions",
                    @"Wind speed -  2min Avg",
                    @"Tech. Name",
                    @"Materials used",
                    @"Notes",
                    @"",
                    nil];
    checkboxItemTexts = [[NSMutableArray alloc] initWithCapacity:0];
    [checkboxItemTexts addObject:@"Fibre materials; Csm, Combi, Roving, UD mat"];
    [checkboxItemTexts addObject:@"Resin; Polyester, Epoxies"];
    [checkboxItemTexts addObject:@"Gel coat"];
    [checkboxItemTexts addObject:@"Top coat"];
    [checkboxItemTexts addObject:@"Hardener"];
    [checkboxItemTexts addObject:@"Filler"];
    [checkboxItemTexts addObject:@"Adhesive; polyester based, epoxy based"];
    [checkboxItemTexts addObject:@"Core materials; balsa, PUR material"];
    [checkboxItemTexts addObject:@"Auxiliary equipment; vortex generators, stall strips, erosion foil, receptor, drain receptor, damper fluid"];
    [checkboxItemTexts addObject:@"Mechanical spares; tip cones, tip wire, hydraulic cylinder, hydraulic hoses, guide block"];
    currentConditionIndex = 0;
    ConditionItems = [[NSMutableArray alloc] initWithObjects:
                      @"Sun",
                      @"Partial Sun",
                      @"Showers",
                      @"Cloudy",
                      @"Rain",
                      @"Indoor",
                      nil
                        ];

    cellStatus = [[NSMutableArray alloc] initWithCapacity:0];
    for (id obj in checkboxItemTexts)
    {
        [cellStatus addObject:@"0"];
    }
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTapped)];
    [tblRepair3 addGestureRecognizer:tapGesture];
    tapGesture.cancelsTouchesInView = NO;
    

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return sectionNames.count;
}

// display header section
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
    return [sectionNames objectAtIndex:section];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // array data for each section
    int number;
    switch (section) {
        case 5:
            number = checkboxItemTexts.count;
            break;
        default:
            number =  1;
            break;
    }
    
    return number;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = [NSString stringWithFormat:@"Cell%d-%d", indexPath.section, indexPath.row];
    UITableViewCell *cell;
    switch (indexPath.section) {
        case 0: //humidity
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SliderCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[SliderCell class]])
                        cell = (SliderCell *)oneObject;
            }
            
            ((SliderCell*)cell).valueSlider.maximumValue  = 95;
            ((SliderCell*)cell).valueSlider.minimumValue  = 5;
            ((SliderCell*)cell).valueSlider.value  = 5;
            ((SliderCell*)cell).valueLalel.text = @"5 %";
            ((SliderCell*)cell).strPostfixValue = @"%";
            break;
        case 1: // temperature
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SliderCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[SliderCell class]])
                        cell = (SliderCell *)oneObject;
            }
            
            ((SliderCell*)cell).valueSlider.maximumValue  = 30;
            ((SliderCell*)cell).valueSlider.minimumValue  = 5;
            ((SliderCell*)cell).valueSlider.value  = 5;
            ((SliderCell*)cell).valueLalel.text = @"5 ˚C";
            ((SliderCell*)cell).strPostfixValue = @"˚C";
            break;
        case 2: // wearther
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            if(cell ==nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
            }

            cell.textLabel.text = ConditionItems[currentConditionIndex];
            break;
        case 3: //wind speed
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SliderCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[SliderCell class]])
                        cell = (SliderCell *)oneObject;
            }
            
            ((SliderCell*)cell).valueSlider.maximumValue  = 14;
            ((SliderCell*)cell).valueSlider.minimumValue  = 0;
            ((SliderCell*)cell).valueSlider.value  = 0;
            ((SliderCell*)cell).valueLalel.text = @"0 m/s";
            ((SliderCell*)cell).strPostfixValue = @"m/s";
            break;
        case 4: //tech name
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EnterDataCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[EnterDataCell class]])
                        cell = (EnterDataCell *)oneObject;
            }

            
            ((EnterDataCell*)cell).tfEnterData.delegate = self;
            break;
        case 5: // checkbox
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CheckBoxCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[CheckBoxCell class]])
                    {
                        cell = (CheckBoxCell *)oneObject;
                        ((CheckBoxCell *)cell).rootController = self; // assign delegate
                    }

            }
            
            
            ((CheckBoxCell *)cell).checkBoxLable.text = [checkboxItemTexts objectAtIndex:indexPath.row];
            ((CheckBoxCell *)cell).changeStateButton.tag = indexPath.row;
            
            if ([cellStatus[indexPath.row] integerValue] == 1)
             {
                 [((CheckBoxCell *)cell) setStatusForCell:YES];
             }
            else
            {
                [((CheckBoxCell *)cell) setStatusForCell:NO];
            }
            
            if(((CheckBoxCell *)cell).isChecked)
            {
                [((CheckBoxCell *)cell) setStatusForCell:YES];
            }
            else
            {
                [((CheckBoxCell *)cell) setStatusForCell:NO];
            }
            
            // set selection style to none
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            break;
        case 6: // note
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TextViewCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[TextViewCell class]])
                    {
                        cell = (TextViewCell *)oneObject;
                    }
                
            }
            ((TextViewCell*)cell).textView.delegate = self;
            break;
            
        case 7: //button
            cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
            
            if (cell == nil)
            {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RepairButtonCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[RepairButtonCell class]])
                    {
                        cell = (RepairButtonCell *)oneObject;
                    }
                
            }

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [((RepairButtonCell*) cell).completeButton addTarget:self action:@selector(btnComplete_Click:) forControlEvents:UIControlEventTouchUpInside];
            [((RepairButtonCell*) cell).addPhotoButton addTarget:self action:@selector(btnAddPhoto_Click:) forControlEvents:UIControlEventTouchUpInside];
            break;
            
        default:
            break;
    }
    
	
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height;
    switch (indexPath.section) {
        case 0: //humidity
        case 1: // temperature
        case 2: //condition
        case 3: //wind speed
        case 4: //tech name
            height = 40;
            break;
        case 5:
            //note
            height = 60;
            break;
        case 6:
            height =120;
            break;
        default:
            height =40;
            break;
            
    }
    
    return height;
}

// selected specified row event handle
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section== 2)
    {
        [self showPicker];
    }
}

#pragma mark - textfield keyboard
-(void)backgroundTapped
{
    [self.view endEditing:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [tfHumidity  resignFirstResponder];
    [tfTemperature resignFirstResponder];
    [tfWeatherConditions resignFirstResponder];
    [tfWinSpeed resignFirstResponder];
    [tfTechName resignFirstResponder];
}


// handle click event of buttons
-(IBAction)btnAddPhoto_Click:(id)sender
{
    NSLog(@"btnAddPhoto_Click");
}

-(IBAction)btnComplete_Click:(id)sender
{
    NSLog(@"btnComplete_Click");
}

-(IBAction)checkBoxButton_Click:(UIButton*)sender
{
    NSLog(@"checkBoxButton_Click");
    [sender setImage:[UIImage imageNamed:@"checkbox_ticked.png"]  forState:UIControlStateHighlighted];
    [tblRepair3 reloadData];
}

-(void) setStatusForCell:(BOOL)status Tag:(int) tag
{
    NSLog(@"setStatusForCell");
    NSString *statusStr = @"0";
    if (status) statusStr = @"1";
    [cellStatus replaceObjectAtIndex:tag withObject:statusStr];
   
}

#pragma textviewdelegate
-(void)textViewDidBeginEditing:(UITextView *)textView
{
   
    tblRepair3.frame = CGRectMake(tblRepair3.frame.origin.x,tblRepair3.frame.origin.y, tblRepair3.frame.size.width, tblRepair3.frame.size.height/2);
    
    // Scroll table view toi do
    CGPoint point = [textView.superview convertPoint:textView.frame.origin toView:tblRepair3];
    NSIndexPath *indexPath = [tblRepair3 indexPathForRowAtPoint:point];
    
    [tblRepair3 scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewRowAnimationTop animated:YES];
   
    
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    tblRepair3.frame = CGRectMake(tblRepair3.frame.origin.x,tblRepair3.frame.origin.y, tblRepair3.frame.size.width, tblRepair3.frame.size.height*2);
    
}

// hide textview
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
        [textView resignFirstResponder];
    return YES;
}

#pragma  Picker

-(void)showPicker
{
    
    [UIView animateWithDuration:0.3f animations:^{
        [view1 setFrame:CGRectMake(0, 160, 320, 260)];
        
    }];
    
    [picker reloadAllComponents];
}

-(void)hidePicker
{
    [UIView animateWithDuration:0.3f animations:^{
        [view1 setFrame:CGRectMake(0, 420, 320, 260)];
        [tblRepair3 setFrame:CGRectMake(0, 0, 320, 420)];
    }];
    
}

// hide picker when click done
-(IBAction)donePicker_Click:(id)sender
{
    [self hidePicker];
}

#pragma mark -UIPicker Datasource
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return ConditionItems.count;

}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString* title = [ConditionItems objectAtIndex:row];
    
    return title;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    currentConditionIndex = row;
    [tblRepair3 reloadData];
}


@end
